﻿using System;
using System.Windows.Media;
namespace XamlKru.Controls
{
    public static class Extensions
    {
        public static Matrix Invert(this Matrix m)
        {
            Double m11, m12, m21, m22, offsetX, offsetY;
            Double s = m.M11 * m.M22 - m.M12 * m.M21;

            m11 =  m.M22;
            m12 = -m.M12;
            m21 = -m.M21;
            m22 =  m.M11;
            offsetX = m.M21 * m.OffsetY - m.M22 * m.OffsetX;
            offsetY = m.M12 * m.OffsetX - m.M11 * m.OffsetY;

            // don't throw, return identity instead
            if (s == 0) return Matrix.Identity;

            return new Matrix(m11 / s, m12 / s, m21 / s, m22 / s, offsetX / s, offsetY / s);
        }
    }
}
